package com.guli.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.commonUtils.vo.CourseVo;
import com.guli.commonUtils.vo.UcenterVO;
import com.guli.edu.client.EduClient;
import com.guli.edu.client.UcenterClient;
import com.guli.edu.entity.Order;
import com.guli.edu.mapper.OrderMapper;
import com.guli.edu.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.edu.utils.OrderNoUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author zxc
 * @since 2023-04-26
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private EduClient eduClient;

    @Autowired
    private UcenterClient ucenterClient;

    @Override
    public String addNewOrder(String courseId, String memberId) {
        // 远程调用微服务模块service-edu中方法，根据课程id，来查询课程基本信息;
        CourseVo courseInfo = eduClient.getBasicCourseInfo(courseId);
        // 远程调用微服务模块service-ucenter中方法，根据会员id，来查询会员基本信息;
        UcenterVO memberInfo = ucenterClient.getMemberInfoByMemberId(memberId);

        Order order = new Order();
        // 设置该新生成订单的订单号
        order.setOrderNo(OrderNoUtil.getOrderNo());
        order.setStatus(0);
        order.setPayType(1);
        BeanUtils.copyProperties(courseInfo , order);
        BeanUtils.copyProperties(memberInfo , order);
        this.save(order);

        return order.getOrderNo();
    }

    @Override
    public Order queryOrderInfoByOrderNo(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no" , orderNo);
        Order order = this.getOne(queryWrapper);
        return order;
    }

    @Override
    public boolean isBuyCourse(String memberId, String courseId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id" , memberId);
        queryWrapper.eq("course_id" , courseId);
        queryWrapper.eq("status" , 1);
        int count = this.count(queryWrapper);
        return (count != 0);
    }
}
